package com.team.gateway.predicates;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
//断言器demo 命名为配置时使用名+RoutePredicateFactory，参考其他内置断言器即可
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public static final String AGE_KEY = "age";

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }
    //从配置中取值为config的域赋值
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge","maxAge");
    }
    //断言逻辑
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange serverWebExchange) {
                String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst(AGE_KEY);
                if (!StringUtils.isEmpty(ageStr)){
                    int age = Integer.parseInt(ageStr);
                    if (age>config.getMinAge()&&age<config.getMaxAge()){
                        return true;
                    }
                }
                return false;
            }

            public String toString() {
                return String.format("minAge: %s,maxAge: %s", config.getMinAge(),config.getMaxAge());
            }
        };
    }

    @Data
    public static class Config {
        private int minAge;
        private int maxAge;
    }
}
